<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="选择地址"
        left-arrow
        @click-left="$router.back()"
      >
      </van-nav-bar>
    </header>
    <div class="content">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="changeAddress"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, AddressList, Toast } from 'vant'
import { getAddressList } from '@/api/address'
import { getStorage } from '../../utils/storage'
import { updateOrderAddress } from '@/api/order'
Vue.use(NavBar)
Vue.use(AddressList)
Vue.use(Toast)
export default {
  data () {
    return {
      list: [],
      chosenAddressId: ''
    }
  },
  mounted () {
    getAddressList({ userid: getStorage('userid') }).then(res => {
      console.log('res', res)
      res.data.data.forEach(item => {
        item.id = item.addressid
        item.address = item.province === item.city
          ? item.province + item.county + item.addressDetail
          : item.province + item.city + item.county + item.addressDetail
      })
      this.list = res.data.data
      // const index = res.data.data.findIndex(item => item.isDefault)
      // this.chosenAddressId = res.data.data[index].id
    })
  },
  methods: {
    changeAddress (item, index) {
      console.log(index, item)
      item.userid = getStorage('userid')
      item.time = this.$route.params.time
      updateOrderAddress(item).then(res => {
        this.$router.back()
      })
    },
    onAdd () {
      Toast('新增地址')
      this.$router.push('/orderaddressadd/' + this.$route.params.time)
    },
    onEdit (item, index) {
      Toast('编辑地址:' + index)
    }
  }
}
</script>
